package com.dis.gateway.filter;

import com.dis.common.exception.UnauthorizedException;
import com.dis.gateway.config.AuthProperties;
import com.dis.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    // exchange：请求上下文。chain：过滤器链
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        log.info("网关收到请求: {}, 完整路径: {}", path, request.getURI());
        
        // 2.判断是否要做登录拦截
        if(exclude(path)){
            // 是不需要校验的路径，直接放行
            log.info("白名单路径: {}, 直接放行", path);
            return chain.filter(exchange);
        }
        
        // 3.获取token——>authorization里可能有多个值
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        if(headers != null && !headers.isEmpty()){
            token = headers.get(0);
            log.info("获取到token: {}", token);
        } else {
            log.warn("未找到authorization请求头");
        }
        
        // 4.校验并解析token 校验token是否为空，解析出用户的id。
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token); //parseToken 已经校验token是否为空了
            log.info("解析出用户ID: {}", userId);
        } catch (UnauthorizedException e) {
            // 拦截，设置相应的状态码为401
            log.error("JWT解析失败: {}", e.getMessage());
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 所有请求终止，后续拦截器不执行
            return response.setComplete();
        }
        
        // 5.传递用户信息——userId
        String userInfo = userId.toString();
        ServerWebExchange newExchange = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();
        
        // 打印所有请求头，确认user-info已添加
        newExchange.getRequest().getHeaders().forEach((key, value) -> {
            log.info("请求头: {} = {}", key, value);
        });

        // 6.放行给下一个拦截器
        return chain.filter(newExchange);
    }
    // 判断路径是否需要做校验
    private boolean exclude(String path) {
        // 拿请求路径与所有可以放行的路径对比
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath,path)){
                return true;
            }
        }
        return false;
    }
    @Override
    public int getOrder() {
        // 过滤器执行顺序，值越小，优先级越高
        return 0;
    }
}